import { createApp, h, ref, onMounted } from 'vue'
import eConfirmDialog from './index.vue'

export interface ConfirmOptions {
  title?: string
  content?: string
  width?: string
  showIcon?: boolean
  iconClass?: string
  showClose?: boolean
  closeOnClickModal?: boolean
  cancelButtonVisible?: boolean
  cancelButtonText?: string
  cancelButtonType?: string
  confirmButtonVisible?: boolean
  confirmButtonText?: string
  confirmButtonType?: string
}

export const eConfirm = (options: ConfirmOptions = {}): Promise<void> => {
  console.log('options=>', options)
  return new Promise((resolve, reject) => {
    // 创建一个挂载点
    const mountNode = document.createElement('div')
    document.body.appendChild(mountNode)

    // 创建一个包装组件来控制对话框的生命周期
    const app = createApp({
      setup() {
        const confirmDialogRef = ref()

        // 使用 onMounted 钩子确保在组件挂载后执行
        onMounted(() => {
          console.log('options:mounted=>', options)
          confirmDialogRef.value.show()
        })

        // 清理函数
        const unmount = () => {
          app.unmount()
          if (mountNode.parentNode) {
            mountNode.parentNode.removeChild(mountNode)
          }
        }

        // 确认回调
        const handleConfirm = () => {
          resolve()
          unmount()
        }

        // 取消回调
        const handleCancel = () => {
          reject(new Error('User cancelled'))
          unmount()
        }

        // 关闭回调
        const handleClose = () => {
          unmount()
        }

        return () =>
          h(eConfirmDialog, {
            ref: confirmDialogRef,
            ...options,
            onConfirm: handleConfirm,
            onCancel: handleCancel,
            onClose: handleClose
          })
      }
    })

    // 挂载应用
    app.mount(mountNode)
  })
}

export default eConfirm
